package com.piesat.quake.common.ftp;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.ftplet.FtpException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class InitFtpServer implements ApplicationRunner, ApplicationListener<ContextClosedEvent> {

    private final FtpServer ftpServer;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            ftpServer.start();
            log.info("ftp server start success...");
        } catch (FtpException e) {
            log.error("ftp server start error:{}", e);
        }
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        if (ftpServer.isStopped()) {
            log.info("ftp已经关闭");
        }
        ftpServer.stop();
        if (ftpServer.isStopped()) {
            log.info("ftp已经关闭");
        } else {
            log.warn("ftp未及时关闭");
        }
    }
}
